package es.us.idinfor.rmplugin.example;

import java.util.HashMap;
import java.util.List;

import Jama.Matrix;

import com.google.common.collect.Lists;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.table.DataRow;
import com.rapidminer.example.table.MemoryExampleTable;
import com.rapidminer.tools.att.AttributeSet;

/**
 * This class is responsible of creating examples.
 * 
 * @author Miguel Angel Alvarez de la Concepcion
 */
public class ExamplesFactory {
	
	/**
	 * This method creates a subset of a example without some features.
	 * This features are indicated by a matrix.
	 * 
	 * @param original The original example set.
	 * @param m The matrix of features.
	 * @return A copy of the original example set.
	 */
	public static ExampleSet getCopy(ExampleSet original, Matrix m) {
		ExampleSet res = getCopy(original);
		
		for(int i = 0; i < m.getRowDimension(); i++) {
			if(m.get(i, i) == -1.0) {
				res.getExampleTable().removeAttribute(i);
			}
		}
		
		return getCopy(res);
	}
	
	/**
	 * This method creates a copy of an example set.
	 * 
	 * @param original The original example set.
	 * @return A copy of the original example set.
	 */
	public static ExampleSet getCopy(ExampleSet original) {
		return getSubSet(original, "");
	}

	/**
	 * This method creates a subset of an example set. If <i>cad</i> is empty string then
	 * the subset will have all the elements.
	 * 
	 * @param original The original example set.
	 * @param cad The label that the examples have.
	 * @return A subset of the original example set.
	 */
	public static ExampleSet getSubSet(ExampleSet original, String cad) {
		MemoryExampleTable table = MemoryExampleTable.createCompleteCopy(original.getExampleTable());
		List<Attribute> attributes = Lists.newArrayList(original.getAttributes());
		AttributeSet set = new AttributeSet(attributes, new HashMap<String, Attribute>());
		Attribute label = original.getAttributes().getLabel();
		
		if(!cad.equals("")) {
			DataRow dr = null;
			int value = label.getMapping().getIndex(cad);
			int i = 0;
			
			while(i < table.size()) {
				dr = table.getDataRow(i);
				
				if(dr.get(label) == value) {
					table.removeDataRow(i);
				}
				else {
					i++;
				}
			}
		}
		
		ExampleSet copy = table.createExampleSet(set);
		copy.getAttributes().setLabel(label);
		
		return copy;
	}
}
